//
//  VideoViewController.m
//  cityStar
//
//  Created by joyban on 15-1-21.
//  Copyright (c) 2015年 tiny. All rights reserved.
//

#import "VideoViewController.h"
#import "SingleTableView.h"
#import <CoreLocation/CoreLocation.h>
#import "selectDistrict.h"

#import "VideoListCell.h"
#import "VideoViewDetailViewController.h"
#import "SVPullToRefresh.h"
#import "VideoPublishViewController.h"
#import "BaseNavController.h"
#import "LoginCityStarViewViewController.h"

NSString *const VideoListCellID = @"videoListCellID";

@interface VideoViewController ()<SingleTableViewDelegate,CLLocationManagerDelegate>

@property (retain, nonatomic) CLLocationManager *locManager;
@property (nonatomic, assign) CLLocationCoordinate2D loc;

@property(weak,nonatomic) IBOutlet UIButton * SelectCitybtn;
@property(weak,nonatomic) IBOutlet UIButton * Alltypebtn;
@property(weak,nonatomic) IBOutlet UIButton * Intelligentschedulingbtn;
@property(weak,nonatomic) IBOutlet UITableView * VideoTable;
@property(nonatomic,strong) NSMutableArray *cityArr;
@property (nonatomic,weak) IBOutlet UIImageView *SelectCityImageView;
@property (strong, nonatomic) SingleTableView *SelectCityTableView;
@property (nonatomic, assign) BOOL isShowAddressList;
@property (nonatomic, weak) IBOutlet UIView *topView;
@property (weak, nonatomic) IBOutlet UIImageView *AlltypeImageView;
@property (strong, nonatomic) SingleTableView *AlltypeTableView;
@property (nonatomic, weak) IBOutlet UIImageView *IntelligentschedulingImageView;
@property (strong, nonatomic) SingleTableView *IntelligentschedulingSingleTableView;
@property (nonatomic, assign) int page;
@property (nonatomic, strong) NSMutableArray *arrayRequest;
@property (nonatomic, weak) IBOutlet UILabel *nothinglabel;
@property (nonatomic, assign) NSString *strOrder;
@property (nonatomic, assign) NSString *strage;
@property (nonatomic, assign) NSString *strDistrict;
@property (nonatomic, assign) NSString *strDistrictid;

@end

@implementation VideoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"租售";
    [self addBackButton];
    [self setUpTableViews];
    __weak typeof(self)weakSelf = self;
    [self addRightButtonWithTitle:@"    发布" actionBlock:^{
        if (weakSelf.currentUser.nickname) {
            VideoPublishViewController *videoPublishVC = [[VideoPublishViewController alloc]init];
            [weakSelf.navigationController pushViewController:videoPublishVC animated:YES];
        }else{
            [weakSelf presentLoginViewController];
        }
    }];
    
    self.strOrder = @"";
    self.strDistrict = @"";
    self.strage = @"";
    
    self.locManager = [[CLLocationManager alloc]init];
    //设置代理
    self.locManager.delegate = self;
    //设置位置经度
    self.locManager.desiredAccuracy = kCLLocationAccuracyBest;
    //设置每隔100米更新位置
    self.locManager.distanceFilter = 100;
    //开始定位服务
    [self.locManager startUpdatingLocation];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeAddressStatues) name:@"isShowAddressList" object:nil];
    self.cityArr = [[NSMutableArray alloc]init];
    [self.cityArr addObject:@"全部区域"];
    self.arrayRequest = [[NSMutableArray alloc]init];
    [self.VideoTable addPullToRefreshWithActionHandler:^{
        self.page = 1;
        [weakSelf webRequest_GetVideoMore:NO];
    }];
    [self.VideoTable addInfiniteScrollingWithActionHandler:^{
        [weakSelf webRequest_GetVideoMore:YES];
    }];
    [self.VideoTable triggerPullToRefresh];
}


#pragma mark - locationDelegate
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

//协议中的方法，作用是每当位置发生更新时会调用的委托方法
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    //结构体，存储位置坐标
    self.loc = [newLocation coordinate];
    //    CLLocation *currentLocation = [INTULocationManager sharedInstance].currentLocation;
    NSString *postUrl  = [NSString stringWithFormat:@"%@%f/%f",KInterFace_location,self.loc.latitude,self.loc.longitude];
    [HttpRequestManager getMethod:postUrl parameters:nil completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
        if (success) {
            DLog(@"%@",response);
            NSString *str = response[@"value"][@"detail"][@"city_code"];
            [self webRequest_citydataWithCityID:str];
        }else{
            
        }
    }];
}

-(void)webRequest_citydataWithCityID:(NSString *)sendeid
{
    NSString *getPul = [NSString stringWithFormat:@"%@/%@",KInterface_getRegion,sendeid];
    [HttpRequestManager getMethod:getPul parameters:nil completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
        if (success) {
            DLog(@"%@",response);
            [[selectDistrict shardDistrictInfo]setClasscityArray:response[@"value"]];
            
            self.cityArr = [[NSMutableArray alloc]init];
            NSArray *array = [[NSArray alloc]init];
            array = [selectDistrict shardDistrictInfo].DistrictArray;
            
            [self.cityArr addObject:@"选择区域"];
            [array enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL *stop) {
                [self.cityArr addObject:obj[@"name"]];
            }];
        }else{
            DLog(@"%@",errMsg);
            [SVProgressHUD showErrorWithStatus:errMsg];
        }
    }];
}

- (void)webRequest_GetVideoMore:(BOOL)isMore
{
    NSString *EndUrl = @"";
    NSString *postUrl = [NSString stringWithFormat:@"%@/type/%d/page/%d/mine/%d",KInterface_PublishList,2,isMore?self.page:0,0];
    EndUrl = postUrl;
    if(![self.strDistrict isEqualToString:@""])
    {
        EndUrl = [NSString stringWithFormat:@"%@/district/%@",EndUrl,self.strDistrictid];
    }
    if(![self.strOrder isEqualToString:@""])
    {
        NSString *strid = @"";
        if([self.strOrder isEqualToString:@"整租"])
        {
            strid = @"1";
        }else if([self.strOrder isEqualToString:@"合租"]){
            strid = @"2";
        }else{
            strid = @"3";
        }
        EndUrl = [NSString stringWithFormat:@"%@/category/%@",EndUrl,strid];
    }
    if(![self.strage isEqualToString:@""])
    {
        NSString *strid = @"";
        if([self.strage isEqualToString:@"按价格低到高排序"])
        {
            strid = @"1";
        }else{
            strid = @"-1";
        }
        EndUrl = [NSString stringWithFormat:@"%@/order/money %@",EndUrl,strid];
    }
    [HttpRequestManager getMethod:[EndUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] parameters:nil completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
        if (success) {
            DLog(@"%@",response);
            if (isMore) {
                [self.arrayRequest addObjectsFromArray:response[@"value"][0][@"content"]];
                self.page = self.page + 1;
            }else{
                self.arrayRequest = [[NSMutableArray alloc]initWithArray:response[@"value"][0][@"content"]];
            }
            [self.VideoTable reloadData];
            if (self.arrayRequest.count == 0) {
                self.nothinglabel.hidden = NO;
            }else{
                self.nothinglabel.hidden = YES;
            }
        }
        if (isMore) {
            [self.VideoTable.infiniteScrollingView stopAnimating];
        }else{
            [self.VideoTable.pullToRefreshView stopAnimating];
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)setUpTableViews
{
    [self.VideoTable registerNib:[VideoListCell nib] forCellReuseIdentifier:VideoListCellID];
}

#pragma mark - UITableViewDelegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [VideoListCell heightOfTableCell];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arrayRequest.count;
}

#pragma mark - UITableViewDataSource
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    VideoListCell *ListdetailCell = [tableView dequeueReusableCellWithIdentifier:VideoListCellID];
    VideoArrayModel *model = [VideoArrayModel objectFromDictionary:self.arrayRequest[indexPath.row]];
    [ListdetailCell setDataVieo:model];
    ListdetailCell.selectionStyle = UITableViewCellSelectionStyleGray;
    return ListdetailCell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    VideoArrayModel *model = [VideoArrayModel objectFromDictionary:self.arrayRequest[indexPath.row]];
    VideoViewDetailViewController *videoViewController = [[VideoViewDetailViewController alloc]init];
    videoViewController.videoModel = model;
    videoViewController.withchType = @"cityService";
    [self.navigationController pushViewController:videoViewController animated:YES];
    [tableView reloadData];
}


-(void)changeAddressStatues
{
    self.isShowAddressList = NO;
}

#pragma mark - Actions
-(IBAction)Alltype_atction:(id)sender
{
    if(self.Alltypebtn.selected == NO)
    {
        self.Alltypebtn.selected = YES;
    }else
    {
        self.Alltypebtn.selected = NO;
    }
    self.Intelligentschedulingbtn.selected = NO;
    self.SelectCitybtn.selected = NO;
    
    [self.AlltypeTableView showFromPosition:CGPointMake(0, 25) inViewController:self dataType:SingleTableViewDataTypeSortModel];
    self.AlltypeTableView.dataArray =  @[@"全部类型",@"合租",@"整租",@"出售"];
}

-(IBAction)Intelligentscheduling_atction:(id)sender
{
    if(self.Intelligentschedulingbtn.selected == NO)
    {
        self.Intelligentschedulingbtn.selected = YES;
    }else
    {
        self.Intelligentschedulingbtn.selected = NO;
    }
    self.SelectCitybtn.selected = NO;
    self.Alltypebtn.selected = NO;
    
    [self.IntelligentschedulingSingleTableView showFromPosition:CGPointMake(0, 25) inViewController:self dataType:SingleTableViewDataTypeSortModel];
    self.IntelligentschedulingSingleTableView.dataArray =@[@"智能排序",@"按价格低到高排序",@"按价格高到低排序"];
}

-(IBAction)SelectCity_action:(id)sender
{
    if(self.SelectCitybtn.selected == NO)
    {
        self.SelectCitybtn.selected = YES;
    }else
    {
        self.SelectCitybtn.selected = NO;
    }
    self.Intelligentschedulingbtn.selected = NO;
    self.Alltypebtn.selected = NO;
    [self.SelectCityTableView showFromPosition:CGPointMake(0, 25) inViewController:self dataType:SingleTableViewDataTypeSortModel];
    self.SelectCityTableView.dataArray = self.cityArr;
}

#pragma mark - singleTableViewDelegate
- (SingleTableView *)AlltypeTableView
{
    if (!_AlltypeTableView) {
        _AlltypeTableView = [[SingleTableView alloc] init];
        _AlltypeTableView.delegate = self;
        [self addChildViewController:_AlltypeTableView];
        [self.view addSubview:_AlltypeTableView.view];
        [self.view bringSubviewToFront:self.topView];
        _AlltypeTableView.arrawImageView = self.AlltypeImageView;
    }
    return _AlltypeTableView;
}

- (void)singleTableView:(SingleTableView *)tableView didSelectedCellAtIndexPath:(NSIndexPath *)indexPath
{
    self.SelectCitybtn.selected = NO;
    self.Alltypebtn.selected = NO;
    self.Intelligentschedulingbtn.selected = NO;
    if (tableView == self.AlltypeTableView) {
        NSString *celltest = @[@"全部类型",@"合租",@"整租",@"出售"][indexPath.row];
        self.strOrder = celltest;
        if([self.strOrder isEqualToString:@"全部类型"])
        {
            self.strOrder = @"";
        }
        if (celltest.length > 4) {
            NSString *btnTitle = [NSString stringWithFormat:@"%@..",[celltest substringWithRange:NSMakeRange(0, 4)]];
            ;
            [self.Alltypebtn setTitle:btnTitle forState:UIControlStateNormal];
        }else{
            [self.Alltypebtn setTitle:celltest forState:UIControlStateNormal];
        }
    }else if (tableView == self.SelectCityTableView)
    {
        NSString *celltest = self.cityArr[indexPath.row];
        self.strDistrict = self.cityArr[indexPath.row];
        NSMutableArray *array = [[NSMutableArray alloc]initWithArray:[selectDistrict shardDistrictInfo].DistrictIdArray];
        [array addObject:@""];
        if([self.strDistrict isEqualToString:@"选择区域"] == YES)
        {
            self.strDistrict = @"";
        }else{
            NSMutableArray *array = [[NSMutableArray alloc]initWithArray:[selectDistrict shardDistrictInfo].DistrictIdArray];
            [array addObject:@""];
            self.strDistrictid = array[indexPath.row-1];
        }
        if (celltest.length > 4) {
            NSString *btnTitle = [NSString stringWithFormat:@"%@..",[celltest substringWithRange:NSMakeRange(0, 4)]];
            [self.SelectCitybtn setTitle:btnTitle forState:UIControlStateNormal];
        }else{
            [self.SelectCitybtn setTitle:celltest forState:UIControlStateNormal];
        }
    }
    else{
        NSString *celltest =@[@"智能排序",@"按价格低到高排序",@"按价格高到低排序"][indexPath.row];
        self.strage = celltest;
        if([self.strage isEqualToString:@"智能排序"])
        {
            self.strage = @"";
        }
        if (celltest.length > 4) {
            NSString *btnTitle = [NSString stringWithFormat:@"%@..",[celltest substringWithRange:NSMakeRange(0, 4)]];
            ;
            [self.Intelligentschedulingbtn setTitle:btnTitle forState:UIControlStateNormal];
        }else{
            [self.Intelligentschedulingbtn setTitle:celltest forState:UIControlStateNormal];
        }
    }
    self.page = 1;
    [self webRequest_GetVideoMore:NO];
}

- (SingleTableView *)IntelligentschedulingSingleTableView
{
    if (!_IntelligentschedulingSingleTableView) {
        _IntelligentschedulingSingleTableView = [[SingleTableView alloc] init];
        _IntelligentschedulingSingleTableView.delegate = self;
        [self addChildViewController:_IntelligentschedulingSingleTableView];
        [self.view addSubview:_IntelligentschedulingSingleTableView.view];
        [self.view bringSubviewToFront:self.topView];
        _IntelligentschedulingSingleTableView.arrawImageView = self.IntelligentschedulingImageView;
    }
    return _IntelligentschedulingSingleTableView;
}

- (SingleTableView *)SelectCityTableView
{
    if (!_SelectCityTableView) {
        _SelectCityTableView = [[SingleTableView alloc] init];
        _SelectCityTableView.delegate = self;
        [self addChildViewController:_SelectCityTableView];
        [self.view addSubview:_SelectCityTableView.view];
        [self.view bringSubviewToFront:self.topView];
        _SelectCityTableView.arrawImageView = self.SelectCityImageView;
    }
    return _SelectCityTableView;
}

-(void)cancleTabelView
{
    self.SelectCitybtn.selected = NO;
    self.Alltypebtn.selected = NO;
    self.Intelligentschedulingbtn.selected = NO;
}

-(void)senderCancle
{
    self.SelectCitybtn.selected = NO;
    self.Alltypebtn.selected = NO;
    self.Intelligentschedulingbtn.selected = NO;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - IsJumpToLoginViewController
-(void)presentLoginViewController
{
    LoginCityStarViewViewController *loginCityStarVC = [[LoginCityStarViewViewController alloc]init];
    BaseNavController *baseloginNav = [[BaseNavController alloc] initWithRootViewController:loginCityStarVC];
    [self presentViewController:baseloginNav animated:YES completion:^{
    }];
}

@end
